package com.bwie.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.domain.TbAddFriend;
import com.bwie.domain.TbFriend;
import com.bwie.mapper.TbAddFriendMapper;
import com.bwie.param.TbFriendParam;
import com.bwie.service.TbFriendService;
import com.bwie.mapper.TbFriendMapper;
import com.bwie.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
* @author xinghe
* @description 针对表【tb_friend(好友表)】的数据库操作Service实现
* @createDate 2025-06-17 13:33:47
*/
@Service
public class TbFriendServiceImpl extends ServiceImpl<TbFriendMapper, TbFriend>
    implements TbFriendService{
    @Autowired
    private TbFriendMapper tbFriendMapper;

    @Autowired
    private TbAddFriendMapper tbAddFriendMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @Override
    public R friendList(TbFriendParam tbFriendParam) {

        Page<TbFriend> page = new Page<>(tbFriendParam.getPage(), tbFriendParam.getLimit());

        Page<TbFriend> tbFriendPage = tbFriendMapper.selectByUserIdPage(page, tbFriendParam);

        return R.OK(tbFriendPage);
    }

    @Override
    @Transactional
    public R deleteByFriend(Integer friendId) {


        TbFriend tbFriend = tbFriendMapper.selectOne(
                new QueryWrapper<TbFriend>().lambda().eq(TbFriend::getFriendId, friendId)
        );
        String key = "tbFriend-" + tbFriend.getUserId();


        TbAddFriend tbAddFriend = new TbAddFriend();
        tbAddFriend.setUserStatus(0);
        tbAddFriendMapper.updateById(tbAddFriend);

        tbFriendMapper.deleteById(tbAddFriend);

        stringRedisTemplate.opsForValue().get(key);

        List<TbFriend> list = tbFriendMapper.selectByUserId(tbFriend.getUserId());
        stringRedisTemplate.opsForValue().set(key, JSON.toJSONString(list),30, TimeUnit.MINUTES);


        return R.OK();
    }
}




